#!/bin/bash

green() { echo -ne "\033[32m$*\033[0m"; } # 输出绿色文本
red() { echo -ne "\033[31m$*\033[0m"; }   # 输出红色文本

# 检查是否为root用户运行
if [[ $EUID -ne 0 ]]; then
	red "Error:脚本必须root用户运行!\n"
	exit 1
fi
cd "$(dirname "$(realpath "$0")")"

# 软件包列表
PACKAGES=("lib32gcc-s1" "libcurl4-gnutls-dev:i386")

# 检查软件包是否已安装
all_packages_installed() {
	for package in "${PACKAGES[@]}"; do
		if ! dpkg -l | grep -qw "^ii  $package"; then
			return 1
		fi
	done
	return 0
}

# 检查并安装软件包
if all_packages_installed; then
	green "所有必需的软件包已安装,跳过预配置步骤。\n"
else
	green "开始预配置环境...\n"
	dpkg --add-architecture i386
	apt update -y
	apt install -y "${PACKAGES[@]}"
	if [ $? -ne 0 ]; then
		red "预配置环境失败!\n"
		exit 1
	fi
	green "预配置环境完成。\n"
fi

# 下载并安装“dst管理面板”
if [ ! -f "/root/dst-admin-go.1.3.1/start.sh" ]; then
	# 是否存在完整安装包
	if ! tar -tf "dst-admin-go.1.3.1.tgz" &>/dev/null; then
		green "开始下载“dst管理面板”。"
		red "(下载过慢请考虑手动上传)\n"
		wget -c -t 4 -T 7 -O dst-admin-go.1.3.1.tgz https://github.com/carrot-hu23/dst-admin-go/releases/download/1.3.1/dst-admin-go.1.3.1.tgz
		if [ $? -ne 0 ]; then
			red "下载“dst管理面板”失败。\n"
			exit 1
		fi
		green "下载“dst管理面板”完成。\n"
	fi
	tar -xvf dst-admin-go.1.3.1.tgz -C /root
	if [ $? -ne 0 ]; then
		red "解压“dst管理面板”失败。\n"
		exit 1
	fi
	rm dst-admin-go.1.3.1.tgz
	# 配置“dst管理面板”
	green "配置“dst管理面板”...\n"
	chmod 755 "/root/dst-admin-go.1.3.1/dst_config"
	cat <<EOF >"/root/dst-admin-go.1.3.1/dst_config"
steamcmd=/root/Steam
force_install_dir=/root/Steam/steamapps/common/Don't Starve Together Dedicated Server
donot_starve_server_directory=
persistent_storage_root=
cluster=MyDediServer
backup=/root/.klei/DoNotStarveTogether/backup
mod_download_path=/root/.klei/DoNotStarveTogether/download_mod
bin=64
beta=0
EOF
	green "“dst管理面板”安装完成。\n"
else
	green "“dst管理面板”已存在,跳过下载。\n"
fi

green "修补“dst管理面板”...\n"
chmod 755 "/root/dst-admin-go.1.3.1/start.sh"
cat <<EOF >/root/dst-admin-go.1.3.1/start.sh
#!/bin/bash
cd "\$(dirname "\$(realpath "\$0")")"
readonly BIN=dst-admin-go
chmod +x \$BIN
PID=\$(pgrep "\$BIN")
start() {
    if [ -z "\$PID" ]; then
        nohup ./\$BIN >log.log 2>&1 &
        echo "“dst管理面板”启动成功"
    else
        echo "“dst管理面板”正在运行..."
    fi
}
stop() {
    if [ -z "\$PID" ]; then
        echo "PID is empty"
    else
        kill -9 \$PID
        echo "“dst管理面板”关闭成功"
    fi
}
restart() {
    stop
    start
}
read -p "请输入操作：1.启动 2.关闭 3.重启：" action
if [ "\$action" == "1" ]; then
    start
elif [ "\$action" == "2" ]; then
    stop
elif [ "\$action" == "3" ]; then
    restart
else
    echo "无效的输入"
fi
EOF
echo "1" | /root/dst-admin-go.1.3.1/start.sh
IP="$(curl -s ifconfig.me)"
green "WebUI已启动,请访问:${IP}:8082\n"
sleep 3
# 下载并安装“SteamCMD”
if [ ! -f "/root/Steam/steamcmd.sh" ]; then
	mkdir -p /root/Steam
	# 是否存在完整安装包
	if ! tar -tf "steamcmd_linux.tar.gz" &>/dev/null; then
		green "开始下载“SteamCMD”。"
		red "(下载过慢请考虑手动上传)\n"
		wget -c -t 4 -T 7 -O steamcmd_linux.tar.gz https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz
		if [ $? -ne 0 ]; then
			red "下载“SteamCMD”失败。\n"
			exit 1
		fi
		green "下载“SteamCMD”完成。\n"
	fi
	tar -xvf steamcmd_linux.tar.gz -C /root/Steam
	if [ $? -ne 0 ]; then
		red "解压“SteamCMD”失败。\n"
		exit 1
	fi
	rm steamcmd_linux.tar.gz
	green "“SteamCMD”安装完成。\n"
else
	green "“SteamCMD”已存在,跳过下载。\n"
fi

# 更新DST服务器
green "开始更新DST服务器...\n"
/root/Steam/steamcmd.sh +login anonymous +app_update 343050 validate +quit
green "dst服务器更新结束。\n"

# 复制必要的库文件
cp "/root/Steam/linux32/libstdc++.so.6" "/root/Steam/steamapps/common/Don't Starve Together Dedicated Server/bin/lib32/libstdc++.so.6"
green "修补DSTmod下载错误bug...\n"
cp "/root/Steam/linux32/steamclient.so" "/root/Steam/steamapps/common/Don't Starve Together Dedicated Server/bin/lib32/steamclient.so"
cp "/root/Steam/linux64/steamclient.so" "/root/Steam/steamapps/common/Don't Starve Together Dedicated Server/bin64/lib64/steamclient.so"
cp "/root/Steam/linux32/steamclient.so" "/root/Steam/steamapps/common/Don't Starve Together Dedicated Server/steamclient.so"
cp "/root/Steam/linux64/steamclient.so" "/root/Steam/steamapps/common/Don't Starve Together Dedicated Server/linux64/steamclient.so"

# 设置交换文件的名称和目标大小
swapfile="/swapfile"
Target_gb=8
i=0
# 确保交换文件名唯一
while [ -e "$swapfile" ]; do
	swapfile="/swapfile$i"
	i=$((i + 1))
done

# 获取系统当前内存和已有的交换空间大小（单位：MB）
Mem_mb=$(free -m | awk '/Mem:/ {print $2}')
Swap_mb=$(free -m | awk '/Swap:/ {print $2}')
Total_mb=$(($Mem_mb + $Swap_mb))
Target_mb=$(($Target_gb * 1024))

# 判断是否需要创建新的交换空间
if [ $((Total_mb + 1)) -lt $Target_mb ]; then

	green "当前总内存小于8GB,创建虚拟内存...\n"
	# 计算需要增加的交换空间大小（单位：MB）
	needed_swap_mb=$(($Target_mb - $Total_mb))

	# 检查磁盘剩余空间是否足够创建交换文件
	available_disk_space_mb=$(df -m / | awk 'NR==2 {print $4}')
	if [ $available_disk_space_mb -lt $(($needed_swap_mb + 1024)) ]; then
		red "磁盘空间不足，无法增加所需的交换空间。\n"
		exit 1
	fi

	# 创建并设置交换文件
	fallocate -l ${needed_swap_mb}M $swapfile
	chmod 600 $swapfile
	mkswap $swapfile >/dev/null
	swapon $swapfile

	# 将新创建的交换文件添加到fstab中，以确保重启后仍然有效
	echo "$swapfile none swap sw 0 0" >>/etc/fstab

	# 写入合适的vm参数
	sysctl -p >/dev/null
	cat <<EOF >>/etc/sysctl.conf
vm.swappiness=20
vm.vfs_cache_pressure=50
vm.dirty_ratio=10
vm.dirty_background_ratio=5
vm.min_free_kbytes=51200
vm.overcommit_memory=0
vm.overcommit_ratio=75
EOF
	sysctl -p >/dev/null
	green "创建虚拟内存成功。\n"
else
	green "当前总内存大于等于8GB,无需增加虚拟内存。\n"
fi

green "所有安装步骤完成。\n"
